<?php
class Mail {

	/**
	 * 发送邮件的调用方法
	 * @param        $mailTo
	 * @param        $mailSubject
	 * @param        $mailBody
	 * @param string $mailFrom
	 * @param bool   $mailSign
	 * @return int
	 */
	public static function send($mailTo, $mailSubject, $mailBody, $mailFrom = '', $mailSign = true) {
		global $DT, $DT_TIME, $db;
		$result  = self::_send($mailTo, $mailSubject, $mailBody, $mailFrom, $mailSign);
		$success = $result == 'SUCCESS' ? 1 : 0;
		if ($DT['mail_log']) {
			$status      = $success ? 3 : 2;
			$note        = $success ? '' : addslashes($result);
			$mailSubject = addslashes(stripslashes($mailSubject));
			$mailBody    = addslashes(stripslashes($mailBody));
			$db->query("INSERT INTO {$db->getPre()}mail_log (email,title,content,addtime,status,note) VALUES ('$mailTo','$mailSubject','$mailBody','$DT_TIME','$status','$note')");
		}
		return $success;
	}



	/**
	 * 发送邮件的方法
	 * @param        $mailTo
	 * @param        $mailSubject
	 * @param        $mailBody
	 * @param string $mailFrom
	 * @param bool   $mailSign
	 * @return int
	 */
	private static function _send($mailTo, $mailSubject, $mailBody, $mailFrom = '', $mailSign = true) {
		global $DT;
		// 关闭发送
		if ($DT['mail_type'] == 'close') return false;

		if ($DT['mail_type'] == 'smtp') {
			$mail = new PHPMailer();

			$mail->CharSet = DT_CHARSET;
			// Set mailer to use SMTP
			$mail->IsSMTP();
			// Specify main and backup server
			$mail->Host = $DT['smtp_host'];
			$mail->Port = $DT['smtp_port'];

			if ($DT['smtp_auth']) {
				// Enable SMTP authentication
				$mail->SMTPAuth = true;
				// SMTP username
				$mail->Username = $DT['smtp_user'];
				// SMTP password
				$mail->Password = $DT['smtp_pass'];
			}

			$mail->From     = $DT['mail_sender'];
			$mail->FromName = $DT['mail_name'] ? $DT['mail_name'] : $DT['site_name'];
			// Add a recipient
			$mail->AddAddress($mailTo);

			$mail->WordWrap = 50; // Set word wrap to 50 characters
			$mail->IsHTML(true); // Set email format to HTML

			$mail->Subject = Str::addSlashes($mailSubject);

			$mail->Body = ($mailSign && $DT['mail_sign']) ? $mailBody . $DT['mail_sign'] : $mailBody;

			if (!$mail->Send()) {
				$errMsg = $DT['smtp_host'] . ':' . $DT['smtp_port'] . ' ' . $mail->ErrorInfo;
				if (defined('TESTMAIL')) Prompt::alert('Error:' . trim($errMsg));
				Log::write($errMsg, 'mail');
				return $mail->ErrorInfo;
			} else {
				return 'SUCCESS';
			}
		} else {
			if ($DT['mail_type'] != 'mail') {
				ini_set('SMTP', $DT['smtp_host']);
				ini_set('smtp_port', $DT['smtp_port']);
				ini_set('sendmail_from', $mailFrom);
			}
			return @mail($mailTo, $mailSubject, $mailBody);
		}
	}

}